<?php


namespace app\admin\middleware;


use app\admin\library\Auth;
use liliuwei\think\Jump;
use think\App;

class AuthCheck
{
    use Jump;

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $controller = $request->controller();
        $action = $request->action();
        $root = $request->root();
        $path = strtolower(str_replace('.', '/', $controller) . '/' . $action);
        $auth = Auth::instance();
        // 设置当前请求的URI
        $auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$auth->match($request->noNeedLogin)) {
            //检测是否登录
            if (!$auth->isLogin()) {
                $url = $request->param('callback/s', '');
                $url = $url ? $url : $request->url();
                $loginUrl = url('index_login', ['callback' => $url]);
                $this->redirect($loginUrl);
            }
            // 判断是否需要验证权限
            if (!$auth->match($request->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$auth->check($path)) {
                    $this->error('无权访问');
                }
            }
        }
        return $next($request);
    }
}